package com.example.alilist.model;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;

import com.example.alilist.utils.ChineseParserUtil;

public class CellphoneModelImp implements ICellphoneModel {

    @Override
    public void loadCellphones(Context context,
            final onLoadCellphonesListener onCellphonesListener) {
        // TODO Auto-generated method stub
        if (context == null || onCellphonesListener == null) {
            return;
        }
        new CellphoneAsyncTask(context, onCellphonesListener).execute();
    }

    private static class CellphoneAsyncTask extends
            AsyncTask<String, Integer, List<CellphoneItem>> {

        private WeakReference<Context> mContextRef;
        private WeakReference<onLoadCellphonesListener> mListenerRef;

        public CellphoneAsyncTask(Context context,
                onLoadCellphonesListener listener) {
            mContextRef = new WeakReference<Context>(context);
            mListenerRef = new WeakReference<onLoadCellphonesListener>(listener);
        }

        @Override
        protected List<CellphoneItem> doInBackground(String... params) {
            // TODO Auto-generated method stub
            if (mContextRef == null || mContextRef.get() == null) {
                return null;
            }
            List<CellphoneItem> cellLists = new ArrayList<CellphoneItem>();
            String[] cols = { ContactsContract.PhoneLookup.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER };
            Cursor cursor = null;
            try {
                cursor = mContextRef
                        .get()
                        .getContentResolver()
                        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                cols, null, null, null);
                for (int i = 0; i < cursor.getCount(); i++) {
                    cursor.moveToPosition(i);
                    int nameIndex = cursor
                            .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                    int numberIndex = cursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    String name = cursor.getString(nameIndex);
                    String number = cursor.getString(numberIndex);
                    CellphoneItem cellphoneItem = new CellphoneItem();
                    cellphoneItem.setName(name);
                    cellphoneItem.setTel(number);
                    String pinyin = ChineseParserUtil.getSpelling(name);
                    String sortString = pinyin.substring(0, 1).toUpperCase();

                    if (sortString.matches("[A-Z]")) {
                        cellphoneItem.setSortLetters(sortString);
                    } else {
                        cellphoneItem.setSortLetters("#");
                    }

                    cellLists.add(cellphoneItem);
                }
            } catch (Exception e) {
                Log.e("CellphoneModelImp", "e=" + e);
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
            Collections.sort(cellLists, new PinyinComparator());
            return cellLists;
        }

        @Override
        protected void onPostExecute(List<CellphoneItem> result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (mListenerRef != null && mListenerRef.get() != null) {
                mListenerRef.get().loadCellphones(result);
            }
        }

    }

}
